package com.example.getappinfodemo

import android.app.AppOpsManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.Settings
import androidx.activity.result.ActivityResultLauncher

/**
 * @作者: smile
 * @时间: 2025/10/21 16:09
 * @描述:
 **/
object Constants {
     fun hasUsageStatsPermission(context: Context): Boolean {
        val appOpsManager = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
        val packageName = context.packageName
        val mode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10+ 用 AppOpsManager.MODE_ALLOWED
            appOpsManager.unsafeCheckOpNoThrow(
                AppOpsManager.OPSTR_GET_USAGE_STATS,
                android.os.Process.myUid(),
                packageName
            )
        } else {
            // Android 10 以下兼容
            @Suppress("DEPRECATION")
            appOpsManager.checkOpNoThrow(
                AppOpsManager.OPSTR_GET_USAGE_STATS,
                android.os.Process.myUid(),
                packageName
            )
        }
        return mode == AppOpsManager.MODE_ALLOWED
    }

    /**
     * 跳转到系统设置页面，并通过Launcher监听返回
     */
    fun requestUsageStatsPermission(
        context: Context,
        launcher: ActivityResultLauncher<Intent>
    ) {
        val intent = Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS).apply {
            data = android.net.Uri.parse("package:${context.packageName}") // 直接定位到当前应用设置
        }
        launcher.launch(intent) // 使用Launcher启动，替代startActivityForResult
    }
}